#include "str.h"

size_t str_alloc_size(const size_t string_len)
{
    size_t alloc_size = 1;

    while (string_len > alloc_size)
    {
        if (alloc_size == 0)
            return 0;

        alloc_size = alloc_size << 1;
    }

    alloc_size += 1; // '\0'

    return alloc_size;
}

str str_create(const char* string)
{
    size_t string_len = strlen(string);
    
    size_t string_alloc_size = str_alloc_size(string_len);

    char* new_str = malloc(2*sizeof(size_t) + string_alloc_size * sizeof(char));

    *((size_t*)new_str) = string_len;

    *((size_t*)new_str + 1) = string_alloc_size;

    new_str += 2*sizeof(size_t); // get pointer of string

    for (size_t i = 0; i < string_len; i++)
        ((char*)new_str)[i] = string[i];

    new_str[string_len] = '\0';

    return new_str;
}

void str_delete(str *string)
{
    *string -= 2*sizeof(size_t); // get start pointer 

    free(*string);

    *string = NULL;
}

size_t str_len(const str string)
{
    return *((size_t*)string - 2);
}

size_t str_alloc(const str string)
{
    return *((size_t*)string - 1);
}